<template>
	<view class="uni-flex-column container">
		<view class="content">
			<view class="detail">
				<!-- 订单标题与状态 -->
				<view class="uni-flex uni-justify-between uni-align-center top">
					<view class="uni-flex uni-align-center">
						<text class="text1">{{ detailData?.title }}</text>
						<text class="text2">{{ detailData?.orderTypeName }}</text>
					</view>
					<text class="text-color"
						v-if="detailData?.orderStatusName==='待服务'">{{ detailData?.orderStatusName }}</text>
					<text class="text-color2"
						v-if="detailData?.orderStatusName==='待付款'">{{ detailData?.orderStatusName }}</text>
					<text class="text3" v-else>{{ detailData?.orderStatusName }}</text>
				</view>

				<!-- 订单服务列表 -->
				<view class="uni-flex content" v-for="item in detailData?.orderServices" :key="item.id">
					<image :src="item?.img" mode="aspectFill"></image>
					<view class="uni-flex-column info">
						<text class="title">{{ item?.name }}</text>
						<text class="des">{{ item?.desc }}</text>
						<text class="num">x {{ item?.count }}</text>
					</view>
					<text class="price">¥{{ item?.priceAmount }}</text>
				</view>

				<!-- 订单价格信息（始终显示：总价、优惠、实付款） -->
				<view class="uni-flex uni-justify-between money-box">
					<text class="text1">订单总价</text>
					<text class="money">¥{{ detailData?.totalAmount }}</text>
				</view>
				<view class="uni-flex uni-justify-between money-box">
					<text class="text1">平台优惠</text>
					<text class="money">¥{{ detailData?.discountAmount }}</text>
				</view>
				<view class="uni-flex uni-justify-between money-box">
					<text class="text1">实付款</text>
					<text class="money">¥{{ detailData?.paymentAmount }}</text>
				</view>

				<!-- 分隔线（始终显示） -->
				<view class="line" v-if="isExpand"></view>

				<!-- 可折叠信息区域：通过 isExpand 控制显示/隐藏 -->
				<view v-if="isExpand">
					<!-- 订单编号（带复制功能） -->
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">订单编号</text>
						<view>
							<text class="text2">{{ detailData?.id }}</text>
							<text class="text3" @click="copyText(detailData.id)">复制</text>
						</view>
					</view>

					<!-- 其他详细信息项 -->
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">服务信息</text>
						<text class="text2">{{ detailData?.serviceInfo }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">服务详情</text>
						<view @click="goOrderDetails()">
							<text class="text2">点击查看</text>
							<uni-icons type="right" size="15" color="#999999"></uni-icons>
						</view>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">订单快照</text>
						<view @click="goorderSnapshot">
							<text class="text2">发生争议时可作为判断依据</text>
							<uni-icons type="right" size="15" color="#999999"></uni-icons>
						</view>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">下单时间</text>
						<text class="text2">{{ detailData?.createOrderTime }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">派（接）单时间</text>
						<text class="text2">{{ detailData?.connectOrderTime }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">预约时间</text>
						<text class="text2">{{ detailData?.advanceOrderTime }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">到达时间</text>
						<text class="text2">{{ detailData?.reachOrderTime }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">结束时间</text>
						<text class="text2">{{ detailData?.endOrderTime }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">评价时间</text>
						<text class="text2">{{ detailData?.evaluateOrderTime }}</text>
					</view>
					<view class="uni-flex uni-justify-between info-item-box">
						<text class="text1">退款时间</text>
						<text class="text2">{{ detailData?.refundOrderTime }}</text>
					</view>
				</view>

				<!-- 折叠/展开按钮：点击切换 isExpand 状态，同步更新图标和文字 -->
				<view class="uni-flex uni-justify-between info-item-box" @click="toggleExpand">
					<text class="text1">更多信息</text>
					<view>
						<text class="text2">{{ isExpand ? '收起' : '展开' }}</text>
						<uni-icons :type="isExpand ? 'down' : 'up'" size="14" color="#999"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 服务保障区域（始终显示） -->
			<view class="service">
				<text class="title">服务保障</text>
				<view class="uni-flex uni-justify-between item">
					<view>
						<image :src="`${$ImgBaseUrl}order_detail_burden.png`" class="icon1" mode="widthFix" />
						<text class="text1">零负担</text>
					</view>
					<view @click="toService(1)">
						<text class="text2">24小时不满意免费重做</text>
						<uni-icons type="right" size="15" color="#999999"></uni-icons>
					</view>
				</view>
				<view class="uni-flex uni-justify-between item">
					<view>
						<image :src="`${$ImgBaseUrl}order_detail_protection.png`" class="icon1" mode="widthFix" />
						<text class="text1">极速维权</text>
					</view>
					<view @click="toService(2)">
						<text class="text2">服务纠纷、平台保障</text>
						<uni-icons type="right" size="15" color="#999999"></uni-icons>
					</view>
				</view>
				<view class="uni-flex uni-justify-between item">
					<view>
						<image :src="`${$ImgBaseUrl}order_detail_proted.png`" class="icon1" mode="widthFix" />
						<text class="text1">隐私保护</text>
					</view>
					<view @click="toService(3)">
						<text class="text2">隐藏手机号，保护隐私</text>
						<uni-icons type="right" size="15" color="#999999"></uni-icons>
					</view>
				</view>
				<view class="complaint">
					<view class="report" @click="toComplaint">
						<image :src="`${$ImgBaseUrl}order_detail_report.png`" mode="widthFix" />
						<text>投诉</text>
					</view>
				</view>
			</view>

			<!-- 评价区域（按原逻辑显示） -->
			<view v-if="['ORDER_CANCEL', 'ORDER_WAIT_EVALUATED'].includes(detailData?.orderStatus)" class="evaluate">
				<text class="tip">您对本次消费的平台服务质量、效果满意吗？</text>
				<view class="uni-flex uni-align-center">
					<view v-for="(item, index) in evaluateList" :key="index"
						class="uni-flex-column uni-align-center item" @click="evaluteClick(index, detailData.id)">
						<image
							:src="selectedIndex === index ? `${$ImgBaseUrl}order_detail_selected.png` : `${$ImgBaseUrl}order_detail_unselected.png`"
							mode="widthFix" />
						<text class="name">{{item}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作栏（始终显示） -->
		<view class="uni-flex uni-justify-between bottom">
			<view class="uni-flex-item uni-flex uni-align-center uni-justify-between menu">
				<l-popover>
					<view class="uni-flex-column more-box">
						<image :src="`${$ImgBaseUrl}more.png`" mode="widthFix" />
						<text class="text1">更多</text>
					</view>
					<template #content>
						<view class="uni-flex-column">
							<text class="power-text" @click="toMore(detailData, 0)">申请开票</text>
							<text class="power-text" @click="toMore(detailData, 1)">删除订单</text>
						</view>
					</template>
				</l-popover>
				<view class="uni-flex-column more-box">
					<image :src="`${$ImgBaseUrl}order_detail_chat.png`" mode="widthFix" />
					<text class="text1">客服</text>
				</view>
				<view class="uni-flex-item uni-flex button-box">
					<text v-if="['ORDER_WAIT_PAYMENT'].includes(detailData.orderStatus)" class="button1"
						@click.stop="toCancel(detailData)">取消订单</text>
					<text v-if="['ORDER_WAIT_PAYMENT'].includes(detailData.orderStatus)" class="button2"
						@click.stop="toPay(detailData)">去付款</text>
					<!--  -->

					<!-- 订单状态为待服务并且服务状态为待服务、已接单、已预约、服务中状态显示申请退款按钮 -->
					<text
						v-if="['ORDER_WAIT_SERVICE'].includes(detailData.orderStatus)&&['SERVICE_WAIT','SERVICE_RECEIVED','SERVICE_ADVANCE','SERVICE_ING'].includes(detailData.serviceStatus)"
						class="button1" @click.stop="handleRefund(detailData)">申请退款</text>

					<!-- 服务状态为待服务、服务中、服务结束显示申请售后按钮 -->
					<text v-if="['SERVICE_WAIT', 'SERVICE_ING', 'SERVICE_END'].includes(detailData.serviceStatus)"
						class="button1" @click.stop="handleAfterSale(detailData)">申请售后</text>

					<text
						v-if="['ORDER_WAIT_EVALUATED'].includes(detailData.orderStatus)&&['SERVICE_END'].includes(detailData.serviceStatus)"
						class="button1" @click.stop="handleEvaluate(detailData.orderServices[0])">去评价</text>


					<text v-if="['SERVICE_END'].includes(detailData.serviceStatus)" class="button2"
						@click.stop="toPayBill(detailData)">再买一单</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		orderDetail,
		OrderDetailsScore
	} from '@/api/consumerOrder.js';
	import useOrder from '../useOrder';

	// 1. 新增折叠状态变量：默认展开（显示所有信息）
	const isExpand = ref(true);

	// 2. 新增折叠/展开切换方法
	const toggleExpand = () => {
		isExpand.value = !isExpand.value;
	};

	// 原逻辑保留
	const {
		handlePay,
		handleCancel,
		handleRefund,
		handleAfterSale,
		handleEvaluate,
		handlePayBill,
		handlePower
	} = useOrder();

	const evaluateList = ['非常满意', '满意', '一般', '不满意', '极差'];
	const selectedIndex = ref(-1);

	const evaluteClick = (index, orderId) => {
		// 如果已经是选中状态，则取消选中（允许重新选择）
		if (selectedIndex.value === index) {
			selectedIndex.value = -1;
		} else {
			selectedIndex.value = index;
		}

		// 立即提交评分（无论是否取消选中）
		const params = {
			orderId: orderId,
			score: selectedIndex.value >= 0 ? selectedIndex.value : null // 取消选中时传递null
		};

		OrderDetailsScore(params).then((res) => {
			console.log('评分提交成功', res);
			uni.showToast({
				title: selectedIndex.value >= 0 ? '评价成功' : '已取消评价',
				icon: 'none'
			});

			// 提交成功后，更新本地数据中的score值
			if (detailData.value) {
				detailData.value.score = selectedIndex.value;
			}
		}).catch(err => {
			console.error('评分提交失败', err);
			uni.showToast({
				title: '评价失败，请重试',
				icon: 'error'
			});

			// 提交失败时恢复原来的选中状态
			if (detailData.value && detailData.value.score !== undefined) {
				selectedIndex.value = detailData.value.score;
			} else {
				selectedIndex.value = -1;
			}
		});
	};


	const toComplaint = () => {
		if (!detailData.value) return;
		uni.navigateTo({
			url: '/pages/order/consumerOrder/complaint?id=' + detailData.value.id
		});
	};

	const copyText = (id) => {
		uni.setClipboardData({
			data: id,
			success: function() {
				uni.showToast({
					title: '复制成功',
					icon: 'none'
				}); // 新增复制反馈
			}
		});
	};

	const toService = (value) => {
		const text = value === 1 ? 'zeroBurden' : value === 2 ? 'protectRights' : 'privacyProtection';
		uni.navigateTo({
			url: '/pages/order/agreement/' + text
		});
	};

	const orderId = ref('');
	const detailData = ref(null);
	const getOrderDetail = () => {
		if (!orderId.value) return;
		orderDetail(orderId.value).then((response) => {
			detailData.value = response.data;

			// 修复：确保正确回显评分
			// 检查score是否存在且是有效数字（0-4）
			if (detailData.value?.score !== undefined && detailData.value.score !== null) {
				const scoreValue = parseInt(detailData.value.score);
				// 确保评分值在有效范围内
				if (!isNaN(scoreValue) && scoreValue >= 0 && scoreValue <= 4) {
					selectedIndex.value = scoreValue;
				} else {
					selectedIndex.value = -1;
				}
			} else {
				selectedIndex.value = -1;
			}
		}).catch(err => {
			uni.showToast({
				title: '获取订单详情失败',
				icon: 'error'
			});
			selectedIndex.value = -1;
		});
	};
	const goorderSnapshot = () => {
		const refundId = detailData.value?.id || ""
		// 关键修正：删除 orderSnapshot 前后的隐形字符，确保路径纯英文无特殊符号
		uni.navigateTo({
			url: `/pages/order/consumerOrder/orderSnapshot?refundId=${refundId}`
		})
	}

	const toPay = () => {
		handlePay(detailData.value)
			.then((res) => {
				uni.showToast({
					title: '支付成功'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/order/consumerOrder/orderList'
					});
				}, 1500);
			})
			.catch((err) => {
				uni.showToast({
					title: err.msg || '支付失败',
					icon: 'error'
				});
				if (err.msg === '请选择服务时间!!!') {
					setTimeout(() => {
						uni.navigateTo({
							url: `/pages/order/consumerOrder/placeOrder?id=${detailData.value.id}`
						})
					}, 1500)
				}
			});
	};

	const toCancel = () => {
		handleCancel(detailData.value)
			.then((res) => {
				uni.showToast({
					title: '取消订单成功'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/order/consumerOrder/orderList'
					});
				}, 1500);
			})
			.catch((err) => {
				uni.showToast({
					title: '取消订单失败',
					icon: 'error'
				});
			});
	};

	const toPayBill = () => {
		handlePayBill(detailData.value)
			.then((res) => {
				uni.showToast({
					title: '跳转成功'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/my/my'
					});
				}, 1500);
			})
			.catch((err) => {
				uni.showToast({
					title: '操作失败',
					icon: 'error'
				});
			});
	};

	const toMore = (data, type) => {
		if (type) {
			handlePower(data, type)
				.then((res) => {
					uni.showToast({
						title: type === 1 ? '删除订单成功' : '申请开票成功'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/order/consumerOrder/orderList'
						});
					}, 1500);
				})
				.catch((err) => {
					uni.showToast({
						title: '操作失败',
						icon: 'error'
					});
				});
		} else {
			handlePower(data, type);
		}
	};
	const goOrderDetails = () => {
		// 1. 判空：避免 detailData 或 orderServices 未加载时报错
		if (!detailData.value || !detailData.value.orderServices || detailData.value.orderServices.length === 0) {
			uni.showToast({
				title: '暂无服务数据',
				icon: 'none'
			});
			return;
		}

		// 2. 提取所有 serviceId → 用逗号拼接为字符串
		const itemIdsStr = detailData.value.orderServices
			.map(item => item.serviceId) // 遍历数组，取每个item的serviceId
			.filter(id => id) // 过滤空值（防止无效ID影响）
			.join(','); // 多ID用逗号分隔（如："123,456,789"）

		// 3. 跳转页面并携带参数 itemIdsStr
		uni.navigateTo({
			url: '/pages/index/index?itemIdsStr=' + itemIdsStr
		});
	};

	const goServiceChange = () => {
		if (!detailData.value) return;
		uni.navigateTo({
			url: '/pages/order/ServiceOrder/ServiceChange?id=' + detailData.value.id
		});
	};

	onMounted(() => {
		getOrderDetail();
	});

	onLoad((option) => {
		orderId.value = option.id || '';
	});
</script>
<style lang="scss" scoped>
	.container {
		background: #f5f5f5;
		height: 100vh;
		box-sizing: border-box;
		padding-top: 24rpx;

		.content {
			flex: 1;
			overflow-y: auto; // 允许滚动
		}

		.detail {
			margin: 0 24rpx;
			padding: 31rpx 39rpx 25rpx 25rpx;
			background: #fff;
			border-radius: 20rpx;
			box-sizing: border-box;

			.top {
				.text1 {
					font-size: 34rpx;
					color: #333333;
					display: inline-block;
					max-width: 300rpx;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
				}

				.text2 {
					font-weight: 400;
					font-size: 24rpx;
					color: #2f80ed;
					background: #e5f0ff;
					border-radius: 4px;
					padding: 2rpx 9rpx;
					margin-left: 14rpx;
				}

				.text3 {
					font-weight: 500;
					font-size: 34rpx;
					color: #999999;
				}

				.text-color {
					font-weight: 500;
					font-size: 34rpx;
					color: #2F80ED;
				}

				.text-color2 {
					font-weight: 500;
					font-size: 34rpx;
					color: #FF6A47;
				}
			}

			.content {
				margin-top: 30rpx;

				image {
					width: 137rpx;
					height: 137rpx;
					border-radius: 10rpx;
				}

				.info {
					flex: 1;
					margin-left: 24rpx;

					.title {
						font-weight: 500;
						font-size: 34rpx;
						color: #333333;
						max-width: 300rpx;
						white-space: nowrap;
						text-overflow: ellipsis;
						overflow: hidden;
					}

					.des {
						font-weight: 400;
						font-size: 28rpx;
						color: #666666;
						margin-top: 5rpx;
						max-width: 350rpx;
						white-space: nowrap;
						text-overflow: ellipsis;
						overflow: hidden;
					}

					.num {
						font-size: 28rpx;
						color: #666666;
						margin-top: 12rpx;
					}
				}

				.price {
					font-weight: 500;
					font-size: 34rpx;
					color: #333333;
				}
			}

			.menu {
				justify-content: flex-end;
				margin-top: 24rpx;

				.button1 {
					font-size: 24rpx;
					color: #333333;
					padding: 12rpx 26rpx;
					border: 1px solid #999999;
					border-radius: 28rpx;
					margin-right: 24rpx;
				}

				.button2 {
					font-size: 24rpx;
					color: #ffffff;
					padding: 12rpx 26rpx;
					background: #2f80ed;
					border-radius: 28rpx;
				}
			}

			.money-box {
				margin-top: 24rpx;

				.text1 {
					font-size: 28rpx;
					color: #333;
				}

				.money {
					font-size: 32rpx;
					color: #333333;
				}

				// &:last-child {
				// 	padding-bottom: 24rpx;
				// 	border-bottom: 1rpx solid #e2e2e2;
				// }
			}

			.line {
				width: 100%;
				border: 1rpx solid #E2E2E2;
				margin: 20rpx 0rpx;
			}

			.info-item-box {
				margin-top: 24rpx;

				.text1 {
					font-size: 28rpx;
					color: #333;
					flex-shrink: 0;
					margin-right: 36rpx;
				}

				.text-collapse {
					font-size: 28rpx;
					color: #333;
					flex-shrink: 0;
				}

				.text2 {
					font-size: 28rpx;
					color: #999999;
					text-align: right;
				}

				.text3 {
					font-size: 28rpx;
					color: #333333;
					margin-left: 30rpx;
				}
			}
		}

		.service {
			margin: 24rpx;
			padding: 31rpx 39rpx 25rpx 25rpx;
			background: #fff;
			border-radius: 20rpx;
			box-sizing: border-box;

			.title {
				font-weight: 500;
				font-size: 34rpx;
				color: #333333;
			}

			.item {
				margin-top: 24rpx;

				.icon1 {
					width: 26rpx;
					height: 26rpx;
					margin-right: 20rpx;
				}

				.icon1 {
					width: 24rpx;
					height: 32rpx;
					margin-right: 20rpx;
				}

				.icon1 {
					width: 24rpx;
					height: 28rpx;
					margin-right: 20rpx;
				}

				.text1 {
					font-size: 28rpx;
					color: #666666;
					flex-shrink: 0;
					margin-right: 48rpx;
				}

				.text2 {
					font-size: 28rpx;
					color: #999999;
					text-align: right;
				}
			}

			.complaint {
				display: flex;
				justify-content: flex-end;
				margin-top: 20rpx;

				.report {
					display: flex;
					align-items: center;
					border-radius: 20rpx;
					border: 1rpx solid #999999;
					padding: 8rpx 25rpx;

					image {
						width: 25rpx;
						height: 25rpx;
						margin-right: 10rpx;
					}

					text {
						font-size: 24rpx;
						color: #999999;
					}
				}
			}
		}

		.evaluate {
			margin: 0 24rpx 24rpx 24rpx;
			padding: 31rpx 39rpx 25rpx 25rpx;
			background: #fff;
			border-radius: 20rpx;
			box-sizing: border-box;

			.tip {
				font-size: 28rpx;
				color: #333333;
			}

			.item {
				flex: 1;
				margin-top: 35rpx;

				image {
					width: 24rpx;
					height: 24rpx;
					margin-bottom: 16rpx;
				}

				.name {
					font-size: 24rpx;
					color: #333333;
				}
			}
		}

		.bottom {
			padding: 22rpx 30rpx 50rpx;
			background: white;

			.menu {
				gap: 38rpx;

				.more-box {
					// margin-right: 38rpx;
					justify-content: center;

					image {
						width: 44rpx;
						height: 44rpx;
					}

					.text1 {
						color: #999999;
						font-size: 24rpx;
					}
				}

				.power-text {
					font-size: 22rpx;
					color: #333333;

					&:not(:last-child) {
						border-bottom: 1rpx solid #e2e2e2;
					}
				}

				.button1 {
					font-size: 24rpx;
					color: #333333;
					padding: 12rpx 26rpx;
					border: 1px solid #999999;
					border-radius: 28rpx;
					margin-left: 24rpx;
				}

				.button2 {
					font-size: 24rpx;
					color: #ffffff;
					padding: 12rpx 26rpx;
					background: #2f80ed;
					border-radius: 28rpx;
					margin-left: 24rpx;
				}

				.button-box {
					justify-content: flex-end;
				}
			}
		}
	}
</style>